package com.kui.web;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.kui.entity.User;
import com.kui.service.UserService;

public class UserServlet extends HttpServlet {

	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute("user");
		
		String m = request.getParameter("m");
		if("member".equals(user.getRole())){
			response.sendRedirect("main.jspx");
			return;
		}
		
		if(m == null){
			UserService us = new UserService();
			List<User> userlist = us.findAll();
			
			request.setAttribute("userlist", userlist);
			request.getRequestDispatcher("WEB-INF/views/user.jsp").forward(request, response);
		}else{
			String uid = request.getParameter("uid");
			if(uid == null || "".equals(uid)){
				response.sendRedirect("usercontrol.jspx");
				return;
			}
			UserService us = new UserService();
			User u = us.findById(uid);
			if(u == null || "admin".equals(u.getRole())  ){
				response.sendRedirect("usercontrol.jspx");
				return;
			}
			
			if("edit".equals(m)){
				u.setRole("admin");
				us.updateRole(u);
				response.sendRedirect("usercontrol.jspx");
			}else if("del".equals(m)){
				us.del(u);
				response.sendRedirect("usercontrol.jspx");
			}else {
				response.sendRedirect("usercontrol.jspx");
			}
		}
		
	}

}
